# -*- coding: utf-8 -*-
"""
PyPipes核心代码包(PyPipes Core Codes)
"""

import sys
import os
import time


class Singleton(object):
    """
    单件模式基类
    """
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance


class CmdlineArguments(Singleton):
    """
    命令行参数解析类

    说明：
    1、以'-'引导的为单字母参数项，参数值紧随其后(有无空格皆可)，无参数值则此项设为 True

       例如: python main.py taskname -uroot -p123456 -c -m "some message"
       那么:
       [0] -> taskname
       ['u'] -> root
       ['p'] -> 123456
       ['c'] -> True
       ['m'] -> some message

    2､ 以'--'引导的为全名称参数项，参数值必须以空格分隔紧随其后，无参数值则此项设为 True
       例如: python main.py taskname --daemon --user mien --password 123456 -R
       那么:
       [0] -> taskname
       ['daemon'] -> True
       ['user'] -> mien
       ['password'] -> 123456
       ['R'] -> True

    3、无参数项名称的参数值，其索引为以0起始的整数
       例如: python main.py taskname --daemon --directory /home fast
       那么:
       [0] -> taskname
       ['daemon'] -> True
       ['directory'] -> /home
       [1] -> fast

    4、参数项后面，再以单独的'-'字符占用一个参数位，可消除对后面的数字索引参数的干扰
       例如: python main.py taskname --ip 133.22.57.8 -b - index.html
       那么:
       [0] -> taskname
       ['ip'] -> 133.22.57.8
       ['b'] -> True
       [1] -> index.html

    5、查询不存在的参数值，返回None
       例如: python main.py taskname -c 100
       那么:
       [0] -> taskname
       ['c'] -> 100

       [1] -> None
       ['aaa'] -> None
       ['notexists'] -> None

    """

    def __init__(self):
        self._dict = {}
        self._parse(sys.argv[1:])  # argv[0]是main.py, 舍弃此项

    def _parse(self, argv):
        index = 0
        key = None

        for arg in argv:
            if arg == '-':
                key = None
            elif arg.startswith('--'):
                arg = arg.lstrip('-')
                if arg:
                    self._dict[arg] = True
                    key = arg
            elif arg.startswith('-'):
                arg = arg.lstrip('-')
                if len(arg) == 1:
                    self._dict[arg] = True
                    key = arg
                else:
                    self._dict[arg[0:1]] = arg[1:]
                    key = None
            else:
                if key:
                    self._dict[key] = arg
                    key = None
                else:
                    self._dict[index] = arg
                    index += 1

    def __getitem__(self, key):
        if key in self._dict:
            return self._dict[key]
        return None

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)


def daemonize():
    """
    守护进程模式
    """
    if os.fork() > 0:
        sys.exit(0)

    os.umask(0)
    os.setsid()

    if os.fork() > 0:
        sys.exit(0)

    sys.stdout.flush()
    sys.stderr.flush()

    r = open('/dev/null', 'r')
    w = open('/dev/null', 'a+')

    os.dup2(r.fileno(), sys.stdin.fileno())
    os.dup2(w.fileno(), sys.stdout.fileno())
    os.dup2(w.fileno(), sys.stderr.fileno())


"""数值定义"""
SECONDS_NUM = {'second': 1, 'minute': 60, 'hour': 3600, 'day': 86400}
BYTES_NUM = {
    'kb': 1024,
    'mb': 1024 * 1024,
    'gb': 1024 * 1024 * 1024,
    'tb': 1024 * 1024 * 1024 * 1024}
